import React, { useState, useEffect, useMemo } from 'react';
import {
  FileExcelOutlined, ProfileOutlined, ReloadOutlined, MinusSquareOutlined, ToolOutlined,
  PlusSquareOutlined, EditOutlined, ExperimentOutlined, CopyOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, Checkbox, DatePicker, Tree, Input } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/shipSRM/chlogo.png'
import ResizableTable from '../newmes/Resizeable_table_min.js';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  getCurrentDate_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
const { Option } = Select;
import Sortable from '../newmes/sortable.js';
import { use_wlfl_initcolmun, use_wlfl_treedata } from './use_baseinfo_config.js';
import useStore from '../../useStore.js'
import { clearCache, useDidCache, useDidRecover, dropByCacheKey } from 'react-router-cache-route';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const wlfl_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_wlfl_initcolmun)
  const [selectedKeys, setselectedKeys] = useState([])
  const [selectedWlfl, setselectedWlfl] = useState([])
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();

  const [showYjfl, setShowYjfl] = useState(false)  //是否显示一级分类弹窗
  const [showZjfl, setShowZjfl] = useState(false)  //是否显示子级分类弹窗

  const [flmc, setFlmc] = useState("")  //分类名称
  const [flbm, setFlbm] = useState("")  //分类编码

  const [treeData, settreeData] = useState([])
  const [selectedlb, setselectedlb] = useState("")

  const filterData = useMemo(() => {
    var filterData = listdata.filter((item) => item.flbm.includes(selectedlb))

    return filterData
  }, [listdata, selectedlb])


  useEffect(() => {
    querylist()
    querywlfllist()
    storage[`Pc_wlfl_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_wlfl_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_wlfl_list__initsize_${storage.userid}`] ? setinitSize(storage[`Pc_wlfl_list__initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])



  const buildTree = (data) => {
    let treeData = []
    console.log("构建树状结构，原始数据:", data)
    
    if (!data || data.length === 0) {
      console.log("没有数据，返回空树")
      return treeData
    }
    
    //一级分类数据
    let yjfl = data.filter(item => item.sjflid == '000')
    console.log("一级分类数据:", yjfl)
    
    for (let i = 0; i < yjfl.length; i++) {
      //一级分类
      let yjflitem = { 
        title: `(${yjfl[i].flbm})${yjfl[i].flmc}`, 
        key: yjfl[i].flbm, 
        value: yjfl[i].flmc, 
        children: [] 
      }
      
      //二级分类数据
      let ejfl = data.filter(item => item.sjflbm == yjfl[i].flbm)
      console.log(`一级分类 ${yjfl[i].flbm} 的二级分类:`, ejfl)
      
      for (let j = 0; j < ejfl.length; j++) {
        let ejflitem = { 
          title: `(${ejfl[j].flbm})${ejfl[j].flmc}`, 
          key: ejfl[j].flbm, 
          value: ejfl[j].flmc, 
          children: [] 
        }
        
        //三级分类数据
        let sjfl = data.filter(item => item.sjflbm == ejfl[j].flbm)
        console.log(`二级分类 ${ejfl[j].flbm} 的三级分类:`, sjfl)
        
        for (let k = 0; k < sjfl.length; k++) {
          let sjflitem = { 
            title: `(${sjfl[k].flbm})${sjfl[k].flmc}`, 
            key: sjfl[k].flbm, 
            value: sjfl[k].flmc 
          }
          //往二级分类中添加三级分类
          ejflitem.children.push(sjflitem)
        }
        //往一级分类中添加二级分类
        yjflitem.children.push(ejflitem)
      }
      treeData.push(yjflitem)
    }
    
    console.log("最终构建的树状数据:", treeData)
    return treeData
  };



  const querywlfllist = async () => {
    try {
      let rtdata = await fetchsync_util("/admin/baseinfo/wlfllb", 'POST', {}, "json")
      console.log("树状数据API返回:", rtdata)
      
      if (rtdata && rtdata.resultdata && rtdata.resultdata.length > 0) {
        var treedata = buildTree(rtdata.resultdata);
        console.log("构建的树状数据:", treedata)
        settreeData(treedata)
      } else {
        console.log("没有获取到树状数据")
        settreeData([])
      }
    } catch (error) {
      console.error("加载树状数据失败:", error)
      settreeData([])
    }
  }

  //路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }

  const querylist = async () => {
    setisloading(true)
    let rtdata = await fetchsync_util("/admin/baseinfo/wlfllb_new", 'POST', {}, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)

    });
    setlistdata(dealnullorundenfined(rtdata.resultdata))
    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
    querywlfllist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_wlfl_item = JSON.stringify({ data: {}, type: "add" })
    history.push({ pathname: "/shipSRM/baseinfo/wlfl_form" });
  }
  /**
   * 编辑
   */
  const handleEdit = async (data, type) => {
    storage.pre_wlfl_item = JSON.stringify({ type, data })
    dropByCacheKey('wlfl_form')
    setnowroute({ ...{ route: "/shipSRM/baseinfo/wlfl_form", title: "物料分类_" + `${type == "edit" ? "编辑" : "查看"}` } })
  }
  /**
   * 删除
   */
  const handledelete = async () => {
    if (selectedKeys.length !== 1) {
      openNotification_util("只可选择一条数据删除!")
    }
    else {
      let rtdata = await fetchsync_util("/admin/baseinfo/delete_wlfl", 'POST', { selectedKeys }, "json")
      rtdata.rtstatus ? querylist() : 1
    }
  }
  /**
   * 导出
   */
  const handleExport = async () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto(selectedRows, filtercol, '物料分类')
  }

  const tree_select = (selectedKeys, info) => {
    console.log("当前点击树节点获取的信息类别为", info.node.value)
    setselectedlb(info.node.id)
  }

  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
    setselectedKeys(checkedKeys.checked)
    setselectedWlfl(info.node.title)
  };

  const tjYjfl = async () => {
    let rtdata = await fetchsync_util("/admin/baseinfo/add_wlfl_yjfl", 'POST', { flbm, flmc }, "json")
    openNotification_util(rtdata.rtmessage)
    querywlfllist()
    querylist()
    setShowYjfl(false)
  };

  const tjZjfl = async () => {
    let rtdata = await fetchsync_util("/admin/baseinfo/add_wlfl_zjfl", 'POST', { flbm, flmc, sjflbm: selectedKeys[0], sjflmc: selectedWlfl }, "json")
    openNotification_util(rtdata.rtmessage)
    querywlfllist()
    querylist()
    setShowZjfl(false)
  };


  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}>

      {/* 左侧：物料分类树状结构 */}
      <div style={{
        width: "25%", height: "92%", position: "absolute", top: "2rem", left: "1%", backgroundColor: "#F7F8FA", color: "black",
        borderRadius: "10px", padding: "1rem"
      }}>
        {/* 树状结构容器 */}
        <div style={{
          width: "100%", 
          height: "100%", 
          backgroundColor: "white", 
          borderRadius: "8px",
          boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
          overflow: "hidden",
          display: "flex",
          flexDirection: "column"
        }}>
          {/* 树状结构标题栏 */}
          <div style={{
            width: "100%",
            height: "3rem",
            backgroundColor: "#a91f24",
            color: "white",
            display: "flex",
            alignItems: "center",
            paddingLeft: "1rem",
            paddingRight: "1rem"
          }}>
            <span style={{ 
              fontSize: "0.9rem", 
              fontWeight: "600"
            }}>
              物料分类树概览
            </span>
          </div>

          {/* 树状结构内容区域 */}
          <div style={{
            flex: 1,
            padding: "1rem",
            overflow: "auto"
          }}>
            {isloading ? (
              <div style={{ 
                width: "100%", 
                height: "100%", 
                display: "flex", 
                justifyContent: "center", 
                alignItems: "center"
              }}>
                <Spin size="small" />
              </div>
            ) : treeData.length == 0 ? (
              <div style={{ 
                width: "100%", 
                height: "100%", 
                display: "flex", 
                justifyContent: "center", 
                alignItems: "center",
                color: "#6c757d",
                fontSize: "0.9rem",
                flexDirection: "column",
                gap: "0.5rem"
              }}>
                <div>暂无分类数据</div>
                <Button 
                  type="link" 
                  size="small"
                  onClick={() => {
                    querywlfllist()
                    querylist()
                  }}
                >
                  点击刷新
                </Button>
              </div>
            ) : (
              <Tree
                treeLine={true}
                style={{
                  width: "100%"
                }}
                checkable
                checkStrictly
                selectedKeys={selectedKeys}
                onCheck={onCheck}
                listHeight={500}
                showSearch
                onSelect={tree_select}
                treeData={treeData}
                showLine={true}
              />
            )}
          </div>
        </div>
      </div>

      {/* 右侧：工具栏和表格区域 */}
      <div style={{
        width: "73%", height: "92%", position: "absolute", top: "2rem", right: "1%", backgroundColor: "#F7F8FA",
        color: "black", borderRadius: "10px", padding: "1rem"
      }}>
        {/* 右侧容器 */}
        <div style={{
          width: "100%", 
          height: "100%", 
          backgroundColor: "white", 
          borderRadius: "8px",
          boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
          overflow: "hidden",
          display: "flex",
          flexDirection: "column"
        }}>
          {/* 工具栏区域 */}
          <div style={{
            width: "100%",
            height: "4rem",
            backgroundColor: "#f8f9fa",
            borderBottom: "1px solid #e9ecef",
            display: "flex",
            alignItems: "center",
            paddingLeft: "1rem",
            paddingRight: "1rem",
            gap: "0.5rem"
          }}>
            <ToolOutlined style={{ fontSize: "1rem", color: "#666666" }} />
            <span style={{ fontSize: "0.8rem", fontWeight: "500", marginRight: "1rem" }}>工具栏</span>
            
            <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷新
            </Button>
            
            <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { setShowYjfl(true) }}>
              <PlusSquareOutlined />新增一级分类
            </Button>
            
            <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => {
                selectedKeys.length == 1 ? setShowZjfl(true) : selectedKeys.length == 0 ? openNotification_util("请先选择分类") :
                  openNotification_util("请选择一个分类")
              }}>
              <PlusSquareOutlined />新增子级分类
            </Button>
            
            <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <EditOutlined /> 编 辑
            </Button>
            
            <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除
            </Button>
            
            <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExport}>
              <FileExcelOutlined />导 出
            </Button>

            <IconFont type="setting" style={{ marginLeft: "auto", fontSize: "1.5rem", color: "#666666" }}
              onClick={e => setIsModalOpen(true)} />
            
            {ifshow && <Sortable tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
              storageName={"Pc_wlfl_list"} open={isModalOpen} handleOpen={(data) => { setIsModalOpen(data); }}
              initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage['Pc_wlfl_list_initsize'] = data; }}
            />}
          </div>

          {/* 表格内容区域 */}
          <div style={{
            flex: 1,
            padding: "1rem",
            overflow: "auto"
          }}>
            {isloading ? (
              <div style={{ 
                width: "100%", 
                height: "100%", 
                display: "flex", 
                justifyContent: "center", 
                alignItems: "center" 
              }}>
                <Spin size="large" />
              </div>
            ) : (
              <ResizableTable 
                tabledata={listdata} 
                tablecolnum={columnarr}
                width="100%"
                storageName={`Pc_wlfl_list_${storage.userid}`}
                czWidth={100}
                sfdoubleclick="false" 
                ifhiddencchangeselecttype="true"
                selectedRows={selectedRows} 
                selectedRowKeys={selectedRowKeys}
                showCz={{ showEdit: true, showView: true, showDelete: true }}
                handleEdit={(data) => handleEdit(data, "edit")}
                handleView={(data) => handleEdit(data, "view")}
                defaultPageSize={15}
                bordered
                scroll={{ x: 'max-content' }}
                handleselectson={(selectedRows, selectedRowKeys) => {
                  setselectedRows(selectedRows)
                  setselectedRowKeys(selectedRowKeys)
                }}
              />
            )}
          </div>
        </div>
      </div>

      <Modal open={showYjfl} title="新增一级分类" onCancel={() => { setShowYjfl(false); setFlmc(""); setFlbm("") }} okText="确定" cancelText="取消" destroyOnClose={true}
        onOk={tjYjfl}
      >
        <div >
          <div>
            <span style={{ color: 'red' }}>*</span>分类名称：<Input value={flmc} onChange={(e) => { setFlmc(e.target.value) }} style={{ width: "70%", marginTop: '1vw' }} />
          </div>
          <div>
            <span style={{ color: 'red' }}>*</span>分类编码：<Input value={flbm} onChange={(e) => { setFlbm(e.target.value) }} style={{ width: "70%", marginTop: '1vw' }} />
          </div>
        </div>
      </Modal>

      <Modal open={showZjfl} title="新增子级分类" onCancel={() => { setShowZjfl(false); setFlmc(""); setFlbm("") }} okText="确定" cancelText="取消" destroyOnClose={true}
        onOk={tjZjfl}
      >
        <div >
          <div>
            <div style={{ width: "30%", display: "inline-block" }}>
              <span style={{ color: 'red' }}>*</span>上级分类名称：
            </div>
            <Input value={selectedWlfl} disabled style={{ width: "70%", marginTop: '1vw' }} />
          </div>
          <div>
            <div style={{ width: "30%", display: "inline-block" }}>
              <span style={{ color: 'red' }}>*</span>上级分类编码：
            </div>
            <Input value={selectedKeys[0]} disabled style={{ width: "70%", marginTop: '1vw' }} />
          </div>
          <div>
            <div style={{ width: "30%", display: "inline-block" }}>
              <span style={{ color: 'red' }}>*</span>分类名称：
            </div>
            <Input value={flmc} onChange={(e) => { setFlmc(e.target.value) }} style={{ width: "70%", marginTop: '1vw' }} />
          </div>
          <div>
            <div style={{ width: "30%", display: "inline-block" }}>
              <span style={{ color: 'red' }}>*</span>分类编码：
            </div>
            <Input value={flbm} onChange={(e) => { setFlbm(e.target.value) }} style={{ width: "70%", marginTop: '1vw' }} />
          </div>
        </div>
      </Modal>



    </div>
  )
}


export default wlfl_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },

  kshcontainer: {
    width: "85vw", minHeight: "40vh", position: "absolute", top: "3vw", left: "15vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
  kshcontainerleft: {
    width: "15%", height: "90%", position: "absolute", top: "3vw", left: "0vw", backgroundColor: "#f7f8fa", color: "black",
    borderRadius: "10px",
  },
}

var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}